﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ContaTelefone.Entities;
using ContaTelefone.Process;
using ContaTelefone.Data;
using System.Net.Mail;

namespace ContaTelefone
{
    public partial class frmEnvio : Form
    {
        ContaEntities _conta;
        DataSet ds;

        public frmEnvio(ContaEntities pConta)
        {
            InitializeComponent();
            _conta = pConta;
            
            NumerosTelProcess objProcess = new NumerosTelProcess();
            dgvRegistros.AutoGenerateColumns = false;
            dgvRegistros.DataSource = objProcess.Listar();

            ReportsRepository rptRepo = new ReportsRepository();
            DataTable dt = rptRepo.getConta(pConta.ID);
            dt.TableName = "VW_VALOR_CCUS";
            ds = new DataSet();
            ds.Tables.Add(dt);
            ds.Tables.Add(PreencheLogo());

            ParametroProcess pp = new ParametroProcess();
            ParametroEntities p = pp.getobj(1);
            if (p != null)
                txtCCGeral.Text = p.VALOR;
        }

        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dgvRow in dgvRegistros.Rows)
            {
                dgvRow.Cells["clnEnviar"].Value = chkAll.Checked;
            }
        }

        private void btnEnviar_Click(object sender, EventArgs e)
        {
            string strNum, strFile, strNome, strEmail;

            ParametroProcess pp = new ParametroProcess();
            ParametroEntities p = pp.getobj(1);
            p.VALOR = txtCCGeral.Text;
            pp.Alterar(p);

            foreach (DataGridViewRow dgvRow in dgvRegistros.Rows)
            {
                strNum = dgvRow.Cells["clnNumero"].Value.ToString();
                strNome = dgvRow.Cells["clnNome"].Value.ToString();
                strEmail = dgvRow.Cells["clnEmail"].Value.ToString();
                strFile = System.IO.Path.Combine(Application.StartupPath, "Conta" + dgvRow.Index + ".pdf");

                if (dgvRow.Cells["clnEnviar"].Value != null)
                {
                    if (dgvRow.Cells["clnEnviar"].Value.ToString() == "true")
                    {
                        ExportToExcel(strFile, strNum);

                        try
                        {
                            SendMail(strEmail, strNome, strFile);
                            WriteLog(string.Format("{0} - Enviado com sucesso!", strNum));
                        }
                        catch (Exception ex)
                        {
                            WriteLog(string.Format("{0} - Erro: {1}", strNum, ex.Message));
                        }
                    }
                }
                Application.DoEvents();
            }

            WriteLog("Fim do envio");
        }

        private void ExportToExcel(string strArquivo, string strCelular)
        {
            Reports.ContaTelefone rptLig = new Reports.ContaTelefone();
            try
            {
                rptLig.SetDataSource(ds);
                rptLig.RecordSelectionFormula = "{VW_CONTA.NumAcs} = '" + strCelular + "'";
                rptLig.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, strArquivo);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void WriteLog(string str)
        {
            txtLog.AppendText(str + "\r\n");
        }

        public void SendMail(string strEmail , string strNome , string strArquivo )
        {
            MailMessage Mailmsg;
            SmtpClient  mSmtpCliente;
            string sBody;

            try
            {
                Mailmsg = new MailMessage();

                Mailmsg.From = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["MailUser"].ToString());
                Mailmsg.To.Add(new MailAddress(strEmail));
                Mailmsg.IsBodyHtml = false;

                Mailmsg.Subject = System.Configuration.ConfigurationManager.AppSettings["MailTitle"].ToString();

                if (! string.IsNullOrEmpty(strArquivo.Trim()))
                    Mailmsg.Attachments.Add(new Attachment(strArquivo));
                
                //Corpo do EMail
                sBody = System.Configuration.ConfigurationManager.AppSettings["MailTitle"].ToString();
                Mailmsg.Body = sBody.Replace("[NOME]", strNome);

                //ENvia o email

                mSmtpCliente = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["MailHost"].ToString());
                mSmtpCliente.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["MailUser"].ToString(), System.Configuration.ConfigurationManager.AppSettings["MailPassword"].ToString());
                mSmtpCliente.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MailPort"]);
                mSmtpCliente.EnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["MailSSL"]);

                mSmtpCliente.Send(Mailmsg);

                Mailmsg.Attachments.Clear();
                Mailmsg = null;
                mSmtpCliente = null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        
        }

        private DataTable PreencheLogo()
        {
            DataTable dt = new DataTable();
            DataRow dr;
            System.Drawing.Bitmap convertImage;

            try
            {
                dt.TableName = "LOGO";
                dt.Columns.Add("IMG_LOGO", typeof(System.Byte[]));
                dr = dt.NewRow();

                try
                {
                    convertImage = new System.Drawing.Bitmap(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.ExecutablePath), "logo.jpg"));
                }
                catch (Exception ex)
                {
                    convertImage = new System.Drawing.Bitmap(100, 40);
                    System.Drawing.Graphics grp = System.Drawing.Graphics.FromImage(convertImage);
                    grp.FillRectangle(Brushes.White, 0, 0, 100, 40);
                    convertImage = new Bitmap(100, 40, grp);
                }


                dr["IMG_LOGO"] = ImageToByteArray(convertImage);

                dt.Rows.Add(dr);

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private Byte[] ImageToByteArray(System.Drawing.Image Imagem)
        {
            try
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                if (Imagem != null)
                    Imagem.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                return ms.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
